/*******************************************************************
 * 外语翻译平台(translate) 
 *
 * 成都一亿信息技术公司 版权所有
 * 
 * Copyright (C) 2010 Transer Information Technology Co., Ltd.
 *
 * @Version : 1.0  2010-12-26 下午05:35:41
 *
 * Mail.java 
 *
 *******************************************************************/
package com.transer.mail;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.ResourceBundle;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.log4j.Logger;

import com.transer.utils.Utils;

/**
 * class defination are there
 * 
 * @author Mark
 * 
 * @version 1.0 ywengineer@gmail.com
 * 
 */
public class Mail {
	private static final Logger logger = Logger.getLogger(Mail.class);

	// 要发送Mail地址
	private List<String> mailTo = new ArrayList<String>();

	private List<String> mailbccTo = new ArrayList<String>();

	private List<String> mailccTo = new ArrayList<String>();

	private List<String> mailFrom = new ArrayList<String>();
	// 是否采用调试方式
	private static boolean debug = true;

	private String messageBasePath = null;
	// Mail主题
	private String subject;
	// Mail内容
	private String msgContent;

	private List<String> attachedFileList = new ArrayList<String>();

	private String messageContentMimeType = "text/html; charset=utf-8";

	private static final Properties props = System.getProperties();

	private static final Session session;

	static {
		ResourceBundle rb = ResourceBundle.getBundle("mail");

		for (String key : rb.keySet()) {
			props.put(key, rb.getString(key));
		}

		debug = Utils.getBoolean(props.getProperty("mail.debug"));

		session = Session.getInstance(props, new Authenticator() {
			/*
			 * (non-Javadoc)
			 * 
			 * @see javax.mail.Authenticator#getPasswordAuthentication()
			 */
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// TODO Auto-generated method stub
				return new PasswordAuthentication(props.getProperty("mail.user"), props.getProperty("mail.pwd"));
			}
		});

		session.setDebug(debug);

		logger.info("初始化邮件发送成功");
	}

	/**
	 * 
	 */
	public Mail(String subject, String content) {
		// TODO Auto-generated constructor stub
		this.subject = subject;
		this.msgContent = content;
	}

	private void fillMail(Session session, MimeMessage msg) throws IOException, MessagingException {
		Multipart mPart = new MimeMultipart();

		InternetAddress[] replyAddress = new InternetAddress[mailFrom.size()];

		for (String from : mailFrom) {
			replyAddress[0] = new InternetAddress(from);
		}

		msg.addFrom(replyAddress);

		if (mailTo.size() < 1) {
			return;
		}

		for (String to : mailTo) {
			InternetAddress[] address = InternetAddress.parse(to);
			msg.addRecipient(Message.RecipientType.TO, address[0]);
		}

		for (String to : mailccTo) {
			InternetAddress[] address = InternetAddress.parse(to);
			msg.addRecipient(Message.RecipientType.CC, address[0]);
		}

		for (String to : mailbccTo) {
			InternetAddress[] address = InternetAddress.parse(to);
			msg.addRecipient(Message.RecipientType.BCC, address[0]);
		}

		msg.setSubject(subject);

		msg.setReplyTo(replyAddress);

		// create and fill the first message part
		MimeBodyPart mBodyContent = new MimeBodyPart();

		if (msgContent != null) {
			mBodyContent.setContent(msgContent, messageContentMimeType);
		} else {
			mBodyContent.setContent("", messageContentMimeType);
		}

		mPart.addBodyPart(mBodyContent);
		// attach the file to the message
		if (attachedFileList != null) {
			for (String fileName : attachedFileList) {
				MimeBodyPart mBodyPart = new MimeBodyPart();

				// attach the file to the message
				FileDataSource fds = new FileDataSource(messageBasePath + fileName);
				System.out.println("Mail发送的附件为：" + messageBasePath + fileName);
				mBodyPart.setDataHandler(new DataHandler(fds));
				mBodyPart.setFileName(fileName);
				mPart.addBodyPart(mBodyPart);
			}
		}
		msg.setContent(mPart);
		msg.setSentDate(new Date());
	}

	public static void main(String[] args) {
		try {
			Mail mail = new Mail("垃圾邮件", "账号注册成功.点<a herf=\"javascript:void(0)\">此处</a>激活");
			mail.addFrom(props.getProperty("mail.user"));
			mail.addMailTo("xcondor@gmail.com");
			mail.sendMail();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 发送e_mail，返回类型为int 当返回值为0时，说明邮件发送成功 当返回值为3时，说明邮件发送失败
	 */
	public int sendMail() throws IOException, MessagingException {
		MimeMessage msg = new MimeMessage(session);
		try {
			fillMail(session, msg);
			Transport.send(msg);
		} catch (MessagingException mex) {
			mex.printStackTrace();
			Exception ex = null;
			if ((ex = mex.getNextException()) != null) {
				System.out.println(ex.toString());
				ex.printStackTrace();
			}
			logger.error("初始化邮件发送失败");
			return 3;
		} finally {

		}
		logger.info("邮件发送成功");
		return 0;
	}

	public void addFrom(String from) {
		mailFrom.add(from);
	}

	public void addMailCCTo(String to) {
		mailccTo.add(to);
	}

	public void addMailBCCTo(String to) {
		mailbccTo.add(to);
	}

	public void addMailTo(String to) {
		mailTo.add(to);
	}

	public void addAttachFile(String file) {
		attachedFileList.add(file);
	}
}
